package com.gcgt.server;

import java.io.FileReader;
import java.io.IOException;
import java.security.Principal;
import java.util.Iterator;

import lt.vin.currency.server.dao.CurrencyDao;

import com.gcgt.client.GreetingService;
import com.gcgt.server.trader.DonatasTrader;
import com.gcgt.server.trader.LineMarket;
import com.gcgt.server.trader.MarketUpdate;
import com.gcgt.server.trader.Trader;
import com.gcgt.server.trader.YahooFinanceCvsIterator;
import com.gcgt.shared.trader.TradingHistory;
import com.gcgt.shared.trader.TradingParameters;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * The server side implementation of the RPC service.
 */
@Singleton
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {


	@Inject CurrencyDao currencyDao;
	
	public String greetServer(String input) throws IllegalArgumentException {
		return "Test message";
	}	


	
	private String getUser() {
		Principal userPrincipal = getThreadLocalRequest().getUserPrincipal();
		if (userPrincipal != null) {
			return userPrincipal.getName();
		} else {
			return null;
		}
	}





	
	
	private boolean isUserTheOwner(String owner) {
		String user = getUser();
		return user != null && user.equalsIgnoreCase(owner);
	}

	@Override
	public TradingHistory getTradingHistory(TradingParameters parameters) throws IOException {
//		Iterator<MarketUpdate> iterator = new YahooFinanceCvsIterator("http://ichart.finance.yahoo.com/table.csv?s=%5EGSPC&d=6&e=26&f=2010&g=d&a=0&b=3&c=1950&ignore=.csv");
		Iterator<MarketUpdate> iterator = new YahooFinanceCvsIterator(new FileReader("table.csv"));

		Trader trader = new DonatasTrader(parameters);
		
		LineMarket market = new LineMarket(iterator);
		market.addTrader(trader);
		
		market.roll(parameters.getStartDate(), parameters.getEndDate());
		
		return trader.getHistory();
	}
}
